import React, { Component, PureComponent } from 'react';
import ReactDOM from 'react-dom';
import { actions } from 'mirrorx';
import moment from 'moment'
import { InputNumber, Select, Form, FormControl, Table, Message, Icon, Upload, Popconfirm } from 'tinper-bee';
import Radio from 'bee-radio';
import queryString from 'query-string';
import Grid from 'components/Grid';
import FormList from 'components/FormList';
import Header from 'components/Header';
import DatePicker from 'bee-datepicker';
import cloneDeep from 'lodash.clonedeep';
import Button from 'components/Button';
import CollapsePanel from 'components/CollapsePanel';
import DelModal from 'components/DelModal';
import Alert from 'components/Alert';
import FormError from 'components/FormError';
import { PurchaseApprovalButton } from 'components/PurchaseApproval';
import RefComponent from 'components/RefComponent'
import ExpenseRedInkModal from './../ExpenseRedInk';
import AcGrids from 'components/AcEditGrid';
const EditGrid = AcGrids.EditGrid;
import { childTableColumn, FormField, FormTableField, SelectCode, headerButtonSets } from '../InitTemplate';


import {
    deepClone, Info, getPageParam, onHandleChildObj, renderRadioInit, CalcuParmForRef,
    initValueString, isEmptyObj, getUUI, renderSelectInit,
    onChangeSelect, resetOfferRefCommon, onEditGridValidate, ControlCommonFor1909
} from "utils";
import './index.less';

const FormItem = FormList.Item;
const format = "YYYY-MM-DD HH:mm:ss";
let { RangePicker } = DatePicker;

class Edit extends Component {
    constructor(props) {
        super(props);
        this.state = {
            currentlist: [],
            refStateParam: {},
            tableHeight: 0,
            selectedIndex: 0, //默认选中行
            editModelVisible: false,
            btnFlag: 0,
            delModalVisible: false, //删除弹框
            showHoverContent: false,
            activeKey: '1',
            childTableColumn: childTableColumn,
            FormField: FormField,
            FormTableField: {},
        }

    }

    componentWillMount(){
        actions.ExpenseConfirmation.getAuth();
    }

    componentDidMount() {
        //计算表格滚动条高度
        sessionStorage.removeItem("errorFields");
        let searchObj = queryString.parse(this.props.location.search);
        let { btnPageFlag, search_id,getDealFlag } = searchObj;
        let self = this;
        let data;
        // if (btnPageFlag == 3) {
        //     data = { id: search_id, type: "0" };
        // } else {
        //     data = { id: search_id, type: "1" };
        // }
        let param = {
            data: search_id,
            callback: (rowData) => {
                if(btnPageFlag == 3) {
                    rowData = this.copyDataDeal(rowData);
                }
                if(rowData.customerCategoryCode == "03"){
                    if(btnPageFlag == 2){
                        this.setState({btnPageFlag : 5})
                    }else if(btnPageFlag == 1){
                        this.setState({btnPageFlag : 4})
                    }
                }
                self.initFilterFactory(rowData, btnPageFlag);
            }
        }
        if (btnPageFlag != 0) {
            actions.ExpenseConfirmation.queryDetail(param);
        } else {
            getUUI();
            let personData = JSON.parse(localStorage.getItem("loginUserInfo")||"{}");
            let {organization=[]} = personData
            organization = organization[0] || {};
            let rowData = {
                organizationId: organization.organizationId,
                organizationName: organization.organizationName,
                organizationCode: organization.organizationCode,
            };
            if(getDealFlag) {
                rowData = this.props.rowData;
            }
            this.initFilterFactory(rowData, btnPageFlag);
            actions.ExpenseConfirmation.updateState({ rowData: rowData, newRowData: {} });
            this.props.form.resetFields();
        }
        if (SelectCode && SelectCode.length > 0) {
            actions.ExpenseConfirmation.getSelectData(SelectCode);
        }
        this.setState({ btnPageFlag, search_id, childTableColumn, FormField, FormTableField });

    }

    setDeafultValues = (rowData,value)=>{
        let param = {
            isDefault:1,
            value:value,
            financeOrganizationId:rowData.organizationId,
            callback:this.setBankAccouontInfo//在这进行默认信息更新
        }
        actions.ExpenseConfirmation.setBankAccountInfo(param);//请求银行账户信息查询接口
    } 

    setBankAccouontInfo = (bankAccouontInfo,value) => {
        if(bankAccouontInfo){
            //如果有默认银行且支付方式是电汇方式，则赋默认值
            if(bankAccouontInfo.content.length>0&&value.refcode=="4"){
                this.props.form.setFieldsValue({
                    bankaccountId:JSON.stringify({refpk:bankAccouontInfo.content[0].id,refcode:bankAccouontInfo.content[0].accountNumber,refname:bankAccouontInfo.content[0].accountName}),
                })
            }
        }
    }

    //设置客户或供应商默认银行账户
    setDefaultPayBankAccount = (type,value) =>{
        let param = {
            value:value.id,
            coumnType:type,
            //在这进行默认信息更新
            callback:this.setPayBankAccouont
        }
        //请求客户或供应商默认银行账户信息查询接口
        actions.ExpenseConfirmation.getDefaultPayBankAccount(param);
    }

    setPayBankAccouont = (result) => {
        if(result){
            this.props.form.setFieldsValue({
                ext09Id:JSON.stringify({refpk:result[0],refcode:result[1],refname:result[2]}),
                ext10:result[3],
            })
        }
    }

    /**
     *
     * @param {Number} pageIndex 跳转指定页数
     */
    freshData = (pageIndex) => {
        this.onPageSelect(pageIndex, 0);
    }

    /**
     *
     * @param {*} index 跳转指定页数
     * @param {*} value 设置一页数据条数
     */
    onDataNumSelect = (index, value) => {
        this.onPageSelect(value, 1);
    }

    onBack = async () => {
        actions.routing.push(
            {
                pathname: '/ExpenseConfirmation-list',
            }
        )
    }

    handleAssin = (newRowData = {}, values) => {
        //let param = Object.assign({}, newRowData, values);
        Object.keys(values).forEach(function (item) {
            if (isEmptyObj(values[item])) {
                values[item] = Object.assign({}, newRowData[item], values[item]);
                !values[item].id ? values[item].persistStatus = 'new' : values[item].persistStatus = 'upd';
                if (!(newRowData[item] instanceof Array) && values[item].id) {
                    values[item].customerId = newRowData.id;
                }
            }
        })
        values = Object.assign({}, newRowData, values);
        return values;
    }


    onEditGridChange = (data, childType, operObj, error) => {
        let { rowData } = this.props;
        if (operObj.operType == "edit") {
            let index = operObj.index;
            if(operObj.field == "taxNum"||operObj.field == "confirmamount"){
                let confirmamount = parseFloat(data[index].confirmamount || 0);  //确认金额
                let taxNum = parseFloat(data[index].taxNum || 0);  //税率
                data[index].notaxamount =  parseFloat(confirmamount/(1+taxNum/100)).toFixed(2);  //不含税额
                data[index].taxamount =  parseFloat(confirmamount-data[index].notaxamount).toFixed(2);  //税额
            }else if (operObj.field == "taxamount") {
                data[index].notaxamount =  parseFloat(parseFloat(data[index].confirmamount || 0)-data[index].taxamount).toFixed(2);  //不含税额; 
            }
            data[index].availableexpenseamount =  parseFloat(data[index].confirmamount || 0-data[index].expenseamount || 0).toFixed(2);  //确认金额-报销金额
            if(!data[index].feeprojectId){
                data[index].feeprojectId = data[index].feeitemId;//费用业务科目带出收支财务项目
                data[index].feeprojectName = data[index].feeitemName;
                data[index].feeprojectCode = data[index].feeitemCode;
            }
        }
        rowData[childType] = data;
        data = data.filter(item => {return item.persistStatus != "fdel"});
        this.setTotal(data);
        actions.ExpenseConfirmation.updateState({ rowData: rowData });
    }

    setTotal = (data) => {
        let confirmamount = 0;
        data.map(item=> {
            confirmamount += parseFloat(item.confirmamount || 0);
        })
        this.props.form.setFieldsValue({
            confirmamount
        })
    }

    onEditGridDel = (data) => {

    }

    save = () => {//保存
        let _this = this;
        let { childTableColumn } = this.state;
        sessionStorage.removeItem("errorFields");
        Object.keys(childTableColumn).forEach(function (item) {
            if (childTableColumn[item].type == "grid") {
                childTableColumn[item].column.map(childItem => {
                    if (typeof childItem.validate == "boolean"  && !childItem.hideField) {
                        childItem.validate = true;
                    }
                })
            }
        })
        this.setState(childTableColumn, () => {
            let errorFields = JSON.parse(sessionStorage.getItem("errorFields"));
            let err = false;
            errorFields && Object.keys(errorFields).forEach(function (item) {
                if (errorFields[item]) {
                    err = item;
                    return;
                }
            })

            if (!err) {
                _this.formDataDeal()
            } else {
                Message.create({ content: `明细字段:行${err} 校验不通过`, color: 'warning', duration: 10 });
                return;
            }
        });
    }

    formDataDeal = () => {//保存
        let { rowData } = this.props;
        let { btnPageFlag } = this.state;

        let _this = this;
        // let btnsaveRef = ReactDOM.findDOMNode(this.refs.saveRef);
        // btnsaveRef.disabled = true;
        _this.props.form.validateFields(async (err, values) => {
            //处理保存的数据
            let data;
            data = onHandleChildObj(values, btnPageFlag, err);
            values = data.values;
            err = data.err;

            //整合table字表与表单
            let param;
            param = this.handleAssin(rowData, values);

            if(sessionStorage.getItem("uui") && btnPageFlag == "0") {
                param.id = sessionStorage.getItem("uui");
            }

            let confirmSon = param.confirmSon.filter(item=>{
                return item.persistStatus != "fdel";
            })
            //删除的明细，不传给后端
            if(btnPageFlag==0){
                param.confirmSon = confirmSon;
            }
            if(!confirmSon || confirmSon.length==0) {
                Message.create({ content: '明细必填一条', color: 'warning', duration: 10 });
                return;
            }
            let tooltipflag;
            let tooltipMessage;
            confirmSon.map(item => {
                if((param.settlementCode == "12" || param.settlementCode == "13" || param.settlementCode == "4" || param.settlementCode == "14" || param.settlementCode == "16")&& (item.taxNum == 0 || !item.taxNum)) {
                    tooltipflag = "明细表存在税率为 0";
                }
                if((param.settlementCode == "12" || param.settlementCode == "13")&& item.taxNum && item.taxNum > 16) {
                    tooltipflag = 1;
                }
                //冲账、折让、票折表头客户和表体客户必须一致(票折现在拆分为两个支付类型)
                if(param.settlementCode==='12'||param.settlementCode==='13'||param.settlementCode==='14'||param.settlementCode==='21'){
                    if (param.customerId&&param.customerId!==item.customerId) {
                        tooltipflag = 2;
                        tooltipMessage = "支付方式为冲账、折让、票折时，表头客户和表体客户必须一致";
                    }
                    if (param.marketareaId&&param.marketareaId!==item.cpaydeptidId){
                        tooltipflag = 2;
                        tooltipMessage = "支付方式为冲账、折让、票折时，表头部门片区和表体费用承担部门必须一致";
                    }
                    if (param.custchantypeId&&param.custchantypeId!==item.custchantypeId){
                        tooltipflag = 2;
                        tooltipMessage = "支付方式为冲账、折让、票折时，表头客户渠道和表体客户渠道必须一致";
                    }
                }
                if(param.settlementId==='1001A11000000001N4AW'||param.settlementId==='1001A11000000001N4AV'){
                    item.taxNum = 13;
                    item.notaxamount =  parseFloat(item.confirmamount/(1+item.taxNum/100)).toFixed(2);  //不含税额
                    item.taxamount =  parseFloat(item.confirmamount-item.notaxamount).toFixed(2);
                }
                if(param.feeBusiTypeCode == 0 && (param.settlementId==='1001A11000000001N4AW'||param.settlementId==='1001A11000000001N4AV')&&param.customerId!=param.payCustomerId){
                    tooltipflag = 2;
                    tooltipMessage = "支付方式为折让、票折时，客户和支付客户必须一致";
                }
                if(param.settlementCode == "21"&&(item.taxNum=="13"||item.taxNum=="0")){
                    tooltipflag = 2;
                    tooltipMessage = "支付方式为票折(其他)时，税率不能为13或0";
                }
            })
            if(tooltipflag && tooltipflag != 1 && tooltipflag != 2) {
                Message.create({ content: tooltipflag, color: 'warning', duration: 5 });
            }
            if(tooltipflag == 1) {
                Message.create({ content: "支付方式为折让、票折，税率不能超过16", color: 'warning', duration: 5 });
                return;
            }
            if(tooltipflag == 2) {
                Message.create({ content: tooltipMessage, color: 'warning', duration: 5 });
                return;
            }

            if (err) {
                Message.create({ content: '必填项未填', color: 'warning', duration: 10 });
            } else {
                if (btnPageFlag == 1) {
                    await actions.ExpenseConfirmation.updateToNCC(
                        { param: param, callback: _this.saveCallBack }
                    );
                } else {
                    await actions.ExpenseConfirmation.save(
                        { param: param, callback: _this.saveCallBack }
                    );
                }
            }
            // btnsaveRef.disabled = false;
        });
    }

    saveCallBack = (data) => {
        let { btnPageFlag } = this.state;
        let tempFlag = btnPageFlag; 
        this.initFilterFactory(data, tempFlag);
        this.setState({btnPageFlag:2});
    }

    copyDataDeal = (data) => {
        delete data.id;
        delete data.code;
        data.persistStatus = "new";
        // if (isEmptyObj(data.mrjtCustomerCompanyDataHeader)) {
        //     delete data.mrjtCustomerCompanyDataHeader.id;
        //     delete data.mrjtCustomerCompanyDataHeader.customerId;
        //     data.mrjtCustomerCompanyDataHeader.persistStatus = "new";
        // }
        // if (isEmptyObj(data.mrjtCustomerCredit)) {
        //     delete data.mrjtCustomerCredit.id;
        //     delete data.mrjtCustomerCredit.customerId;
        //     data.mrjtCustomerCredit.persistStatus = "new";
        // }
        if (data.mrjtCustomerAddressList && data.mrjtCustomerAddressList.length > 0) {
            data.mrjtCustomerAddressList.map(item => {
                delete item.id;
                delete item.customerId;
                item.persistStatus = "new";
            })
        }
        if (data.mrjtCustomerContactList && data.mrjtCustomerContactList.length > 0) {
            data.mrjtCustomerContactList.map(item => {
                delete item.id;
                delete item.customerId;
                item.persistStatus = "new";
            })
        }
        if (data.mrjtCustomerAccountList && data.mrjtCustomerAccountList.length > 0) {
            data.mrjtCustomerAccountList.map(item => {
                delete item.id;
                delete item.customerId;
                item.persistStatus = "new";
            })
        }
        if (data.mrjtCustomerFinanceList && data.mrjtCustomerFinanceList.length > 0) {
            data.mrjtCustomerFinanceList.map(item => {
                delete item.id;
                item.persistStatus = "new";
            })
        }
        if (data.relateCustomerList && data.relateCustomerList.length > 0) {
            data.relateCustomerList.map(item => {
                delete item.id;
                delete item.customerId;
                item.persistStatus = "new";
            })
        }
        if (data.mrjtCustomerMaterialsUsedList && data.mrjtCustomerMaterialsUsedList.length > 0) {
            data.mrjtCustomerMaterialsUsedList.map(item => {
                delete item.id;
                item.persistStatus = "new";
            })
        }
        if (data.mrjtCustomerChangeHistoryList && data.mrjtCustomerChangeHistoryList.length > 0) {
            data.mrjtCustomerChangeHistoryList.map(item => {
                delete item.id;
                delete item.customerId;
                item.persistStatus = "new";
            })
        }
        if (data.mrjtCustomerRankList && data.mrjtCustomerRankList.length > 0) {
            data.mrjtCustomerRankList.map(item => {
                delete item.id;
                delete item.customerId;
                item.persistStatus = "new";
            })
        }
        delete data.confirmAttachments;
        return data;
    }


    // 动态显示标题
    onChangeHead = (btnPageFlag) => {
        let titleArr = ["新增", "编辑", "详情", "复制","编辑","详情"];
        return titleArr[btnPageFlag] || '新增';
    }

    /**
     *
     * @param {Number} value  pageIndex 或者 pageIndex
     * @param {Number} type 为0标识为 pageIndex,为1标识 pageSize
     */
    onPageSelect = (value, type) => {
        let queryParam = deepClone(this.props.queryParam);
        queryParam['pageParams'] = getPageParam(value, type, queryParam.pageParams);
        this.setState({ selectedIndex: 0 }); //默认选中第一行
        actions.ExpenseConfirmation.loadList(queryParam);
    }

    /**
     *
     * @param {Number} btnFlag 弹框框状态 0为添加、1为修改、2为详情
     */
    onClickShowModel = (btnFlag, childType, index = -1, record = {}) => {
        let { rowData } = this.props;
        if (!rowData) rowData = {}
        //let ColumnsData = eval(`this.Columns${childType}`);
        let ColumnsData = FormTableField[childType];
        this.setState({
            editModelVisible: true,
            btnFlag,
            childType: childType,
            selectedIndex: index,
            currentRecord: record,
            currentlist: rowData[childType] || []
            //ColumnsData: ColumnsData
        });
    }

    /**
     * 关闭修改model
     */
    onCloseEdit = (data, childTypeback) => {
        let { childType, btnPageFlag, selectedIndex, btnFlag } = this.state;
        let childTypetemp = childTypeback || childType
        let {  rowData } = this.props;
        this.setState({
            editModelVisible: false,
            btnFlag: -1,
        });
        if (!data) return;
        if (!rowData) rowData = {};
        
        if (btnFlag == 0 && !rowData[childTypetemp]) {
            rowData[childTypetemp] = [];
        }
        if (data.persistStatus == "new" && btnPageFlag == "0" || childTypeback == "confirmAttachments") {
            rowData[childTypetemp].push(data);
        } else {
            rowData[childTypetemp][selectedIndex] = data;
        }

        if(btnPageFlag != 0){
            this.saveFile(rowData);
        } 
        actions.ExpenseConfirmation.updateState({rowData: rowData });
        this.forceUpdate();
    }

    /**
     *
     * @param {Number} type 1、取消 2、确定
     * @returns {Promise<void>}
     */
    confirmGoBack(type) {
        this.setState({ delModalVisible: false });
        let tempRowData;
        if (type === 1) { // 确定
            const { currentlist, childType, selectedIndex, currentRecord, search_id,btnPageFlag } = this.state;
            const { newRowData, rowData } = this.props;
            tempRowData = cloneDeep(rowData);
            if (tempRowData[childType][selectedIndex].persistStatus == 'new') {
                tempRowData[childType].splice(selectedIndex, 1);
            } else {
                tempRowData[childType][selectedIndex].persistStatus = "fdel";
            }
            if (childType == "confirmAttachments" && btnPageFlag!=0) {

                let param = {
                    data: search_id || rowData.id,
                    file: tempRowData
                }
                actions.ExpenseConfirmation.submitFile(param);
            }
            actions.ExpenseConfirmation.updateState({ newRowData: newRowData, rowData: tempRowData });
        }
    }

    /**
     * 删除modal 显示
     */
    onClickDel = (childType, record, selectedIndex) => {
        this.setState({
            delModalVisible: true,
            editModelVisible: false,
            selectedIndex: selectedIndex,
            currentRecord: record,
            childType: childType
        });
    }

    //拼接下级级联的上级参数值
    calcuParm = (item, data, fieldName, childType) => {
        let { refStateParam } = this.state;
        let tempParam = {};
        let cascadeName = item.cascadeName;
        // let param = item.param;
        // if(!param)  param={};
        if (!cascadeName) return param;
        //待优化 先取一个级联参数
        let paramName = cascadeName[0];

        tempParam[paramName] = data[0] && data[0].refpk || null;
        //param 配置数据里的固定参数
        //tempParam 依赖字段计算出来的参数
        //tempParam = Object.assign({}, param, tempParam);
        let _thisParmField = `${fieldName}_${childType}`;
        refStateParam[_thisParmField] = tempParam;
        this.setState({ refStateParam });
    }
    //重置下级级联参照
    resetOfferRef = (item, childType, childRowData) => {
        if (!item.offers) return;
        let param = {}
        param[item.offers] = null;
        //重置级联下级参照值
        this.props.form.setFieldsValue(param);
    }

    getRefParam = (item, childType) => {
        let { refStateParam } = this.state;
        let cascadeName = item.cascadeName;
        if (!cascadeName) return {};
        let {
            alias,
        } = cascadeName;
        let _thisParmField = `${alias}_${childType}`;
        Object.keys(refStateParam).forEach(function (key) {
            if (key == _thisParmField) {
                return refStateParam[_thisParmField];
            }
        })
        return {};
    }

    initFilterFactory = (rowData={}, btnPageFlag) => {
        let childFields, controlData, value;
        let searchObj = queryString.parse(this.props.location.search);
        let { getDealFlag } = searchObj;
        let self = this;
        Object.keys(FormField).forEach(function (item) {
            childFields = FormField[item]["Field"];
            childFields.forEach((filed) => {
                controlData = rowData;
                if (item.search("DataHeader") == -1) {
                    controlData = rowData[item];
                }
                //根据字段值隐藏字段
                if(filed.enname == "redbillcode") {
                    filed.hidepage[2] = rowData[filed.enname]==null? true:false
                }
                if(filed.enname == "feeitemId" && rowData.limitFeeItem) {
                    filed.param["ZHEN_code"] = rowData.limitFeeItem
                }else if(filed.enname == "feeitemId" && !rowData.limitFeeItem) {
                    delete filed.param.ZHEN_code;
                }

                if (filed.hidecolumns) {
                    if (filed.hidecolumns.offerfields) {
                        value = rowData[filed.hidecolumns.offerfields];
                    }
                    self.hideColumnSaleorder(filed, value, true);
                }
                if (filed.cascadeChildTable) {//初始化的时候添加过滤
                    filed.cascadeChildTable.map(item => {
                        if (rowData[item.childType] && rowData[item.childType].length > 0) {
                            rowData[item.childType].map(itemdata => {
                                if(item.dtoKey=="organizationId"){
                                    itemdata[item.dtoKey] = controlData[item.dtoKey];
                                }
                            })
                        }
                    })
                    actions.ExpenseConfirmation.updateState({ rowData: rowData });
                }
                ControlCommonFor1909(controlData, filed, btnPageFlag, self, true,{ bakFormField: FormField, bakFormTableField: FormTableField, bakchildTableColumn: childTableColumn });
               
            })
        })
        Object.keys(childTableColumn).forEach(function (item) {
            if(item=="confirmSon"){
                childFields = childTableColumn[item]["column"];
                childFields.forEach((column) => {
                    //根据字段值必填字段
                    if(column.dataIndex == "feeitemName") {
                        if(rowData.feeitemCode=="1104"){
                            delete column.filedProps.aliasparam[0].paramkey;
                            column.filedProps.constparam["ZHEN_code"] = rowData.feeitemCode;
                        }else{
                            column.filedProps.aliasparam[0]["paramkey"] = "ZHEN_code";
                        }
                        if(rowData.ext07){
                            column.filedProps.constparam["ZHEN_bottom_code"] = rowData.ext07;
                        }else{
                            delete column.filedProps.constparam.ZHEN_bottom_code;
                        }
                    }else if(column.dataIndex == "feeitemName"&&column.filedProps.constparam["ZHEN_code"]=="1104"){
                        delete column.filedProps.constparam.ZHEN_code;
                    }
                })
            }
        })
    }

    setInvoiceCode = ()=>{
        let {rowData} = this.props;
        let childFields;
        Object.keys(childTableColumn).forEach(function (item) {
            if(item=="confirmSon"){
                childFields = childTableColumn[item]["column"];
                childFields.forEach((column) => {
                    //根据字段值必填字段
                    if(column.dataIndex == "memo") {
                        column.required = (rowData["billtypeCode"]=="35-Cxx-001"&&rowData["settlementId"]=="0001Z0100000000000Y3")||(rowData["billtypeCode"]=="35-Cxx-006"&&rowData["settlementId"]=="1001A11000000001N4AX")?true:false;
                    }
                })
            }
        })
        actions.ActivityProgram.updateState({ rowData: rowData});
    }

    renderFormItem = (ColumnsData, childRowData = {}, childType) => {
        let { getFieldProps, getFieldError } = this.props.form;
        let { selectDataList = {},rowData={} } = this.props;
        let { btnPageFlag } = this.state;
        let dom = [];
        let enname, codename, showname, required, hidepage, showpage;
        let self = this;

        ColumnsData && ColumnsData.forEach((item, index) => {
            enname = childType.search("DataHeader") == -1 ? `${childType}.${item.enname}` : `${item.enname}`;
            required = item.required;
            hidepage = item.hidepage;
            if (hidepage && hidepage[btnPageFlag]) {
                showpage = false;
            } else {
                showpage = true;
            }
            switch (item.type) {
                case 'FormControl':
                    showpage && dom.push(<FormItem
                        className="time"
                        key={item.enname}
                        required={item.required}
                        size={item.componentClass && "md"}
                        FormError={<FormError errorMsg={getFieldError(`${enname}`)} />}
                        label={item.zhname}
                    >
                        <FormControl
                            key={`${item.enname}${index}`}
                            componentClass={item.componentClass || "input"}
                            disabled={!item.edit || btnPageFlag == 2 ||  btnPageFlag == 5 || btnPageFlag == 5}
                            {...getFieldProps(`${enname}`, {
                                initialValue: childRowData[item.enname] || "",
                                rules: [
                                    {
                                        required: required,
                                        message: "请输入",
                                    },
                                    {
                                        pattern: item.pattern || /^[\w\W]{0,100}$/,
                                        message:<span>{item.message || "超长度"}</span>,
                                    }
                                ],
                            })}
                        />
                    </FormItem>);
                    break;
                case 'InputNumber':
                    showpage && dom.push(<FormItem
                        className="time"
                        key={item.enname}
                        required={item.required}
                        FormError={<FormError errorMsg={getFieldError(`${enname}`)} />}
                        label={item.zhname}
                    >
                        <InputNumber toThousands={true}
                            key={`${item.enname}${index}`} max={item.max}
                            min={item.min} step={item.step || 1} precision={item.precision || 2}
                            iconStyle="one" step={1} disabled={!item.edit || btnPageFlag == 2 ||  btnPageFlag == 5 || btnPageFlag == 5}
                            {...getFieldProps(`${enname}`, {
                                initialValue: childRowData[item.enname],
                                rules: [{ required: required, message: "请输入" }],
                            })}
                        />

                    </FormItem>);
                    break;
                case 'DatePicker':
                    showpage && dom.push(<FormItem
                        className="time"
                        key={item.enname}
                        required={item.required}
                        FormError={<FormError errorMsg={getFieldError(`${enname}`)} />}
                        label={item.zhname}
                    >
                        <DatePicker
                            key={`${item.enname}${index}`}
                            className='form-item' format={item.format || format} disabled={!item.edit || btnPageFlag == 2 ||  btnPageFlag == 5 || btnPageFlag == 5}
                            {...getFieldProps(`${enname}`, {
                                initialValue: childRowData && childRowData[item.enname] && moment(childRowData[item.enname]) || item.defaultValue,
                                rules: [{
                                    required: required,
                                    message: '请选择',
                                }],
                            })}
                        />
                    </FormItem>);
                    break;
                case 'RangePicker':
                    dom.push(<FormItem
                        className="time"
                        key={item.enname}
                        required={item.required}
                        FormError={<FormError errorMsg={getFieldError(`${item.enname}`)} />}
                        label={item.zhname}
                    >
                        <RangePicker
                            key={`${item.enname}${index}`}
                            dateInputPlaceholder={['开始', '结束']}
                            disabled={!item.edit}
                            {...getFieldProps(`${item.enname}`, {
                                initialValue: [moment(), moment()],
                                rules: [{ required: required, message: '请选择', }],
                            })}
                        />
                    </FormItem>);
                    break;
                case 'RefComponent':
                    //this.initFilterFactory(item,childRowData);
                    showpage && dom.push(<FormItem
                        className="time"
                        ref={item.enname}
                        key={item.enname}
                        required={item.required}
                        FormError={<FormError errorMsg={getFieldError(`${enname}`)} />}
                        label={item.zhname}
                    >
                        <RefComponent
                            disabled={!item.edit || btnPageFlag == 2 ||  btnPageFlag == 5 || btnPageFlag == 5}
                            multiple={item.multiple || false}
                            key={`${item.enname}${index}`}
                            constparam={item.param}
                            aliasparam={self.state.refStateParam}
                            aliasfieldName={item.alias}
                            title={item.zhname}
                            refName={item.refname}
                            childType={childType}
                            fieldName={enname}
                            treeNodeDisabledKey={item.treeNodeDisabledKey}
                            clearMatchData={this.clearMatch}
                            rules={[
                                {
                                    required: required,
                                    message: '请选择',
                                    pattern: item.required && /[^{"refname":"","refpk":"","refcode":""}|{"refpk":"","refname":"","refcode":""}]/
                                }
                            ]}
                            initialValue={initValueString(
                                childRowData[item.showname],
                                childRowData[item.enname],
                                item.required,
                                childRowData[item.codename],
                            )}
                            refTableOnClickSave={(refName, fieldName, data) => {
                                ControlCommonFor1909(data[0], item, btnPageFlag, self,"ExpenseConfirmation");
                                if (item.relation && data[0]) {
                                    resetOfferRefCommon(self, item.relation, data, childType);
                                }
                                if (item.hidecolumns) {
                                    self.hideColumnSaleorder(item, data);
                                }
                                if (item.cascadeChildTable) {
                                    let value;
                                    item.cascadeChildTable.map(itemfield => {
                                        value = data[0] && data[0][itemfield.refKey];
                                        if (rowData[itemfield.childType] && rowData[itemfield.childType].length > 0) {
                                            rowData[itemfield.childType].map(itemdata => {
                                                itemdata[itemfield.dtoKey] = value;
                                            })
                                        }
                                    })
                                    actions.ExpenseConfirmation.updateState({ rowData: rowData });
                                }
                                if(item.enname == "settlementId" && data[0]) {
                                    self.setChildTableTax(data[0]);
                                    self.setDeafultValues(rowData,data[0]);
                                }
                                if((item.enname == "paySupplerId"||item.enname == "payCustomerId") && data[0]) {
                                    self.setDefaultPayBankAccount(item.enname,data[0]);
                                }
                                //根据字段值设置必不必填
                                if (item.enname=="settlementId" && data[0]) {
                                    childRowData["settlementId"] = data[0].id;
                                    this.setInvoiceCode();
                                }
                            }}
                            refTreeOnClickSave={(refName, fieldName, data) => {

                                ControlCommonFor1909(data[0], item, btnPageFlag, self,"ExpenseConfirmation");

                                if (item.relation && data[0]) {
                                    resetOfferRefCommon(self, item.relation, data, childType);
                                }
                                if (item.cascadeChildTable) {
                                    let value;
                                    item.cascadeChildTable.map(itemfield => {
                                        value = data[0] && data[0][itemfield.refKey];
                                        if (rowData[itemfield.childType] && rowData[itemfield.childType].length > 0) {
                                            rowData[itemfield.childType].map(itemdata => {
                                                itemdata[itemfield.dtoKey] = value;
                                            })
                                        }
                                    })
                                    actions.ExpenseConfirmation.updateState({ rowData: rowData });
                                }
                               
                            }}
                            form={self.props.form}
                        />
                    </FormItem>);
                    break;
                case 'Select':
                    let options = selectDataList[item.code] || item.options;
                    showpage && dom.push(<FormItem
                        className="time"
                        key={item.enname}
                        required={item.required}
                        FormError={<FormError errorMsg={getFieldError(childType.search("DataHeader") == -1 ? `${childType}.${item.codename}` : `${item.codename}`)} />}
                        label={item.zhname}
                    >
                        <Select
                            key={`${item.enname}${index}`}
                            onSelect={(value, props) => {
                                onChangeSelect(self, props, item, childType);
                                if (item.relation && value) {
                                    resetOfferRefCommon(self, item.relation, value, childType);
                                }
                                if (item.enname=="billtypeId") {
                                    childRowData["billtypeCode"]=value;
                                    this.setInvoiceCode();
                                }
                                if (item.enname == "feeBusiTypeId"){
                                    if(!value) return;
                                    this.props.form.setFieldsValue({
                                        ext09Id:null,
                                        ext09Code:null,
                                        ext09Name:null,
                                        ext10:null,
                                    })
                                }
                                ControlCommonFor1909(value, item, btnPageFlag, self,"ExpenseConfirmation");
                            }}
                            disabled={item.disablecontrol && item.disablecontrol[btnPageFlag] || !item.edit || btnPageFlag == 2 ||  btnPageFlag == 5 || btnPageFlag == 5}
                            {
                            ...getFieldProps(childType.search("DataHeader") == -1 ? `${childType}.${item.codename}` : `${item.codename}`, {
                                initialValue: renderSelectInit(childRowData[item.codename], item.defaultValue),
                                rules: [{
                                    required: required,
                                    message: '请选择',
                                }],
                            })
                            }
                        >
                            <Option value="">请选择</Option>
                            {
                                options && options.map((item, index) => {
                                    return (
                                        <Option key={`${item.code}${index}`} id={item.id} value={item.code}>{item.name}</Option>
                                    )
                                })
                            }

                        </Select>
                        <FormControl className="hide"
                            {...getFieldProps(childType.search("DataHeader") == -1 ? `${childType}.${item.showname}` : `${item.showname}`, {
                                initialValue: childRowData[`${item.showname}`] || "",
                            })}
                        />
                        <FormControl className="hide"
                            {...getFieldProps(childType.search("DataHeader") == -1 ? `${childType}.${item.enname}` : `${item.enname}`, {
                                initialValue: childRowData[`${item.enname}`] || "",
                            })}
                        />
                    </FormItem>);
                    break;
                case 'Radio':

                    showpage && dom.push(<FormItem
                        className="time"
                        key={item.enname}
                        required={item.required}
                        FormError={<FormError errorMsg={getFieldError(`${enname}`)} />}
                        label={item.zhname}
                    >
                        <Radio.RadioGroup
                            key={`${item.enname}${index}`}
                            //className={(!item.edit || btnPageFlag ==2) && "disabled"}
                            {
                            ...getFieldProps(childType.search("DataHeader") == -1 ? `${childType}.${item.enname}` : `${item.enname}`, {
                                initialValue: renderRadioInit(childRowData[item.enname], item.defaultValue),
                                rules: [{
                                    required: required,
                                    message: '请选择',
                                }],
                            }
                            )}
                        >
                            {
                                item.options && item.options.map((itemoption, index) => {
                                    return (
                                        <Radio
                                            disabled={!item.edit || btnPageFlag == 2 ||  btnPageFlag == 5}
                                            key={index} value={itemoption.key}>{itemoption.value}</Radio>
                                    )
                                })
                            }
                        </Radio.RadioGroup>
                    </FormItem>);
                    break;
                default: break;
            }
        })
        return dom;
    }

    //同步NCC
    syncNCC = () => {
        let self = this;
        let { rowData } = self.props;
        actions.ExpenseConfirmation.syncNCC(rowData);
    }

    //标记支付
    ButtonSignPay = () => {
        let self = this;
        let { rowData } = self.props;
        let currentButton = headerButtonSets[1];
        let ids = rowData.id;
        let param = {
            data: {
                key:'1',
                ids:ids
            },
            header: {
                url: currentButton.url,
                method: currentButton.method,
                ContentType: currentButton.ContentType
            }
        }
        actions.ExpenseConfirmation.ButtonSetsModel(param);
        actions.routing.push(
            {
                pathname: '/ExpenseConfirmation-list',
            }
        )
    }
    
    //取消标记支付
    ButtonDisSignPay = () => {
        let self = this;
        let { rowData } = self.props;
        let currentButton = headerButtonSets[2];
        let ids = rowData.id;
        let param = {
            data: {
                key:'0',
                ids:ids
            },
            header: {
                url: currentButton.url,
                method: currentButton.method,
                ContentType: currentButton.ContentType
            }
        }
        actions.ExpenseConfirmation.ButtonSetsModel(param);
        actions.routing.push(
            {
                pathname: '/ExpenseConfirmation-list',
            }
        )
    }
    
    //标记签收
    ButtonSignReceive = () => {
        let self = this;
        let { rowData } = self.props;
        let currentButton = headerButtonSets[0];
        let ids = rowData.id;
        let param = {
            data: {
                ids:ids
            },
            header: {
                url: currentButton.url,
                method: currentButton.method,
                ContentType: currentButton.ContentType
            }
        }
        actions.ExpenseConfirmation.ButtonSetsModel(param);
        actions.routing.push(
            {
                pathname: '/ExpenseConfirmation-list',
            }
        )
    }

    //详情页的编辑和复制转换
    onToEdit = (type) => {
        let self = this;
        return () => {
            let { rowData } = this.props;
            if(type == 3) {
                rowData = this.copyDataDeal(rowData);
            }
            this.initFilterFactory(rowData, type);
            this.setState({ btnPageFlag: type, FormField: FormField });
            
        }
    }

    setChildTableTax = (data) => {
        let {rowData} = this.props;
        if(!rowData.confirmSon || rowData.confirmSon.length==0) return;
        if(data.refcode == "13" || data.refcode == "12") {
            rowData.confirmSon.map(item => {
                item.taxNum = 13
                item.notaxamount =  parseFloat(item.confirmamount/(1+item.taxNum/100)).toFixed(2);  //不含税额
                item.taxamount =  parseFloat(item.confirmamount-item.notaxamount).toFixed(2);
            })
        }
        if(data.refcode == "21"){
            rowData.confirmSon.map(item => {
                item.taxNum = 6
                item.notaxamount =  parseFloat(item.confirmamount/(1+item.taxNum/100)).toFixed(2);  //不含税额
                item.taxamount =  parseFloat(item.confirmamount-item.notaxamount).toFixed(2);
            })
        }
    }
    
    //虚拟关联方的时候 只有供应商名称和供应商基本分类可以显示
    hideAll = (value,data) =>{
        let searchObj = queryString.parse(this.props.location.search);
        let { btnPageFlag } = searchObj;
        let { rowData } = this.props;
        let assignRowData=cloneDeep(rowData);
        let formValue = this.props.form.getFieldsValue();
        formValue = onHandleChildObj(formValue, btnPageFlag, null);
        assignRowData = Object.assign({}, assignRowData, formValue.values);
        assignRowData.customerCategoryId = data.refpk;
        assignRowData.customerCategoryCode = data.refcode;
        assignRowData.customerCategoryName = data.refname;
        
        
        if(value == "03"){
            this.initFilterFactory(assignRowData,4);
            this.setState({ btnPageFlag: 4 })
            
        }else{
            if(btnPageFlag == 2 || btnPageFlag == 4) btnPageFlag = 1;
            this.initFilterFactory(assignRowData,btnPageFlag)
            this.setState({ btnPageFlag: btnPageFlag });
        }
    }

    //详情页的编辑和复制转换
    // onToEdit = (type) => {
    //     return () => {
    //         if (type == 3) {
    //             let { search_id } = this.state;
    //             let param = { id: search_id, type: "0" };
    //             actions.ExpenseConfirmation.queryDetail(param);
    //         }
    //         this.setState({ btnPageFlag: type })
    //     }
    // }

    //详情页的删除操作
    onDel = () => {
        let { search_id } = this.state;
        actions.ExpenseConfirmation.delItem({
            ids: search_id
        });
        actions.routing.goBack();
    }

    hideColumnSaleorder = (item, data, initFlag) => {
        let hidecolumns = item.hidecolumns;
        let self = this;
        let value, flag;;
        if (initFlag || item.type != "RefComponent" || !data[0]) {
            value = data
        } else if (item.type == "RefComponent") {
            value = data[0][hidecolumns.currentkey];
        }

        if (hidecolumns.show) {
            if (typeof value == "number") {
                flag = hidecolumns.value != value;
            } else {
                flag = hidecolumns.value.search(value) == -1
            }

        } else {
            if (typeof value == "number") {
                flag = hidecolumns.value == value;
            } else {
                flag = hidecolumns.value.search(value) !== -1
            }
        }
        self.hideColumnCommon(flag, hidecolumns.columns);
    }

    hideColumnCommon = (flag, showFileds) => {
        let { childTableColumn } = this.state;
        childTableColumn.mrjtCustomerAddressList.column.map(item => {
            if (showFileds.indexOf(item.dataIndex) !== -1) {
                item.hideField = flag
            }
        })
        this.setState(childTableColumn);
    }

    resetmrjtCustomerCompanyDataHeader = (fbmrjtCustomerCompanyDataHeader) => {
        let param = {};
        Object.keys(fbmrjtCustomerCompanyDataHeader).forEach( item => {
            if (item == "taxArrearsRecord" || item == "openingNotice" || item == "litigationAnnouncement" || item == "insuranceSituation"
                || item == "foreignInvestment" || item == "equity" || item == "movableFinancing" || item == "informationDisclosure") {

                param[`${item}`] = fbmrjtCustomerCompanyDataHeader[item];

            } else {
                if (item == "currencyId") {
                    let values = this.props.form.getFieldsValue(["countryId"]);
                    let flag = values.countryId && JSON.parse(values.countryId).refcode == "CN"
                    param[`currencyId`] = `{"require":${flag},"refpk":"${fbmrjtCustomerCompanyDataHeader["currencyId"] || ''}","refcode":"${fbmrjtCustomerCompanyDataHeader["currencyCode"] || ''}","refname":"${fbmrjtCustomerCompanyDataHeader["currencyName"] || ''}"}`;
                } else {
                    param[`${item}`] = fbmrjtCustomerCompanyDataHeader[item];
                }
            }
        })
        if( !param.registeredCapital) {
            param.registeredCapital = -1;
        }
        
        this.props.form.setFieldsValue(param);
    }

    renderFormFiled = () => {
        let { rowData = {} } = this.props;
        let { btnPageFlag } = this.state;
        let { FormField } = this.state;
        let authCodeList = JSON.parse(sessionStorage.getItem("ExpenseConfirmation") || "[]");
        let FormDom = [];
        let hidePanel;
        let hidepage, showpage;
        //if(!isEmptyObj(rowData)) return FormDom;
        for (let item in FormField) {
            let renderData;
            if (item.search("DataHeader") != -1) {
                renderData = rowData;
            }
            // else if (item == "mrjtCustomerCompanyDataHeader" && isEmptyObj(fbmrjtCustomerCompanyDataHeader)) {
            //     renderData = fbmrjtCustomerCompanyDataHeader;
            // }
            else {
                renderData = rowData && rowData[item] || {};
            }

            hidepage = FormField[item].hidepage;
            if (hidepage && hidepage[btnPageFlag]) {
                showpage = false;
            } else {
                showpage = true;
            }
            hidePanel = false;
            if(btnPageFlag==1 && item=="DataHeader" && authCodeList.indexOf("9901-05-03-21") == -1){
                hidePanel=true;
            }
            if(btnPageFlag==1 && item=="mrjtCustomerCompanyDataHeader" && authCodeList.indexOf("9901-05-03-18") == -1){
                hidePanel=true;
            }
            if(btnPageFlag==1 && item=="mrjtCustomerCredit" && authCodeList.indexOf("9901-05-03-19") == -1){
                hidePanel=true;
            }
            if(btnPageFlag==1 && item=="mrjtCustomerFactoryInformationListDataHeader" && authCodeList.indexOf("9901-05-03-20") == -1){
                hidePanel=true;
            }

            if (showpage) {
                FormDom.push(<CollapsePanel in={true} key={FormField[item].title} title={FormField[item].title}>
                    <FormList size="sm">
                        {this.renderFormItem(FormField[item].Field, renderData, item)}
                    </FormList>
                </CollapsePanel>)
            }
        }
        return FormDom;
    }

    //启用
    ButtonEnable = (item, index, record) => {
        let { rowData } = this.props;
        let url;
        if (item == "mrjtCustomerAddressList") {
            url = "customer-address/batch-enable";
        } else if (item == "mrjtCustomerFinanceList") {
            url = "customer-finance/batch-enable";
        } else if (item == "mrjtCustomerContactList") {
            url = "customer-contact/batch-enable"
        }else if(item == "mrjtCustomerAccountList") {
            url = "customer-account/batch-enable"
        }

        let param = {
            data: {
                ids: record.id || "1"
            },
            header: {
                url: url,
                method: 'post',
                ContentType: 'application/x-www-form-urlencoded;charset=utf-8'
            }
        }
        actions.ExpenseConfirmation.ButtonSetsModel(param);

        rowData[item][index].isEnable = 1;
    }

    //停用
    ButtonDisable = (item, index, record) => {
        let { rowData } = this.props;
        let url;
        if (item == "mrjtCustomerAddressList") {
            url = "customer-address/batch-disable";
        } else if (item == "mrjtCustomerFinanceList") {
            url = "customer-finance/batch-disable";
        } else if (item == "mrjtCustomerContactList") {
            url = "customer-contact/batch-disable"
        }else if(item == "mrjtCustomerAccountList") {
            url = "customer-account/batch-disable"
        }
        let param = {
            data: {
                ids: record.id || "1"
            },
            header: {
                url: url,
                method: 'post',
                ContentType: 'application/x-www-form-urlencoded;charset=utf-8'
            }
        }
        actions.ExpenseConfirmation.ButtonSetsModel(param);

        rowData[item][index].isEnable = 2;
    }

    saveFile = (rowData) => {
        let { search_id } = this.state;
        let param = {
            data: search_id || rowData.id,
            file: rowData
        }
        actions.ExpenseConfirmation.submitFile(param);
    }

    checkFile = (record) => {
        let url =  record.fileUrl + `?attname=${record.filename}`;
        window.open(url);
    }

    previewFile = (record) => {
        let url =  "http://ow365.cn/?i=24375&furl="+`${GROBAL_HTTP}`+record.fileUrl + `?attname=${record.filename}`;
        window.open(url);
    }

    checkInvioce = (record) => {
        let data={
            url:`${GROBAL_HTTP}`+record.fileUrl,
            id:record.id,
            filename:record.filename,
            callback:this.setInvoiceInfo//在这进行默认信息更新
        }
        actions.ExpenseConfirmation.checkInvioce(data);
    }

    setInvoiceInfo = (filename,data) => {
        let {rowData} = this.props;
        if(!rowData.confirmAttachments || rowData.confirmAttachments.length==0) return;
        rowData.confirmAttachments.forEach(function(item){
            if(item.filename == filename){
                if (data&&data.data) {
                    if (data.data.invoice_number) {
                        item.ext01 = data.data.invoice_number;
                    }
                    if (data.data.message) {
                        item.ext02 = data.data.message;
                    }
                    if (data.data.total_amount) {
                        item.ext03 = data.data.total_amount;
                    }
                    if (data.message) {
                        item.ext04 = data.message;
                    }
                }
            }
        })
    }

    //收藏单据
    collectBill = () => {
        let self = this;
        let { rowData } = self.props;
        let data = {ids:rowData.id};
        actions.ExpenseConfirmation.collectBill({data:data,callback:(res)=>{
            if(res.status==1) {
                Message.create({ content: res.message, color: 'danger', duration: 10 });
                return;
            }else{
                Message.create({ content: res.message, color: 'success', duration: 10 });
                return;
            }
        }});
    }

    //取消收藏
    cancelCollectBill = () => {
        let self = this;
        let { rowData } = self.props;
        let data = {ids:rowData.id};
        actions.ExpenseConfirmation.cancelCollectBill({data:data,callback:(res)=>{
            if(res.status==1) {
                Message.create({ content: res.message, color: 'danger', duration: 10 });
                return;
            }else{
                Message.create({ content: res.message, color: 'success', duration: 10 });
                return;
            }
        }});
    }

    pushOper = (_column, item, billState) => {
        let _this = this;
        let searchObj = queryString.parse(this.props.location.search);
        let { btnPageFlag } = this.state;
        if (!isEmptyObj(_column) && _column[_column.length - 1].title == "操作") {
            _column.pop();
        }

        if (!isEmptyObj(_column) && _column[_column.length - 1].title !== "操作") {
            _column && _column.push({
                title: "操作",
                dataIndex: "d",
                key: "d",
                width: 100,
                fixed: "right",
                render(text, record, index) {
                    return (
                        <div className='operation-btn'>
                            {item == "confirmAttachments" && <i title="预览附件" size='sm' className='uf uf-search' onClick={() => { _this.previewFile(record) }}></i>}
                            {item == "confirmAttachments" && <i title="下载附件" size='sm' className='uf uf-download' onClick={() => { _this.checkFile(record) }}></i>}
                            {item == "confirmAttachments" && !record.ext02 && <i title="发票验证" size='sm' className='uf uf-camera' onClick={() => { _this.checkInvioce(record) }}></i>}
                            {billState ===0 && item == "confirmAttachments" && <i title="删除" size='sm' className='uf uf-del' onClick={() => { _this.onClickDel(item, record, index) }}></i>}

                            {btnPageFlag == "2" && record.isEnable !== 1 && (item == "mrjtCustomerAddressList" || item == "mrjtCustomerContactList" || item == "mrjtCustomerFinanceList" || item == "mrjtCustomerAccountList") && <i title="启用" size='sm' className='uf uf-play' onClick={() => { _this.ButtonEnable(item, index, record) }}></i>}
                            {btnPageFlag == "2" && record.isEnable === 1 && (item == "mrjtCustomerAddressList" || item == "mrjtCustomerContactList" || item == "mrjtCustomerFinanceList" || item == "mrjtCustomerAccountList") && <i title="停用" size='sm' className='uf uf-reduce-c' onClick={() => { _this.ButtonDisable(item, index, record) }}></i>}
                        </div>
                    )
                }
            })
        }
        return _column;
    }

    renderaliaCustomer = (fieldName, data) => {
        actions.ExpenseConfirmation.getAliaCustomer(data[0].id);
    }

    onGetTaxpayerNumber = () => {
        let { rowData = {} } = this.props;
        let { btnPageFlag } = this.state;
        let value = this.props.form.getFieldValue("name");
        let englishName = this.props.form.getFieldValue("englishName");
        let source = 0;
        if (btnPageFlag == "1" && value == rowData.name) {
            source = 1
        }
        let param = {
            customerName: value,
            englishName:englishName,
            source: source,
        }
        if (!value) {
            Message.create({ content: "请输入客户名称", color: 'warning', duration: 10 });
            return;
        }
        actions.ExpenseConfirmation.getTaxpayerNumber({ param, "callback": this.resetmrjtCustomerCompanyDataHeader });

    }

    renderTableFiled = () => {
        let { rowData, showLoading, aliaCustomerList } = this.props;
        let authCodeList = JSON.parse(sessionStorage.getItem("ExpenseConfirmation") || "[]");
        let { personName } = this.props.personData
        let { childTableColumn, FormField, FormTableField } = this.state;
        let { tableHeight, btnPageFlag } = this.state;
        let hidepage, showpage, hideBtns = {};
        let type, tempColumn, _column, gridData;
        let FormDom = [];
        let sortObj = {
            mode: 'multiple',
            backSource: true
        }
        if (!rowData) rowData = {};

        let _this = this;

        let groupname;
        if (btnPageFlag == 0) {
            groupname = sessionStorage.getItem("uui");
        }else {
            groupname = rowData.id;
        }
        //文件上传
        const fileUpload = {
            name: 'fileList',
            action: '/iuap-saas-filesystem-service/file/upload',     //上传地址
            data: { 
                groupname: groupname, 
                filepath: groupname, 
                url: true, 
                isreplace: false 
            },
            headers: {
            },
            showUploadList: false,
            beforeUpload(file) {
                var fileSize = file.size / (1024 * 1024)
                if(fileSize>11) {
                    Message.create({ content: "文件大小不能超过11MB！", color: 'warning', duration: 10 });
                    return false
                }
                if(this.splitFileName(file.name).length>20) {
                    Message.create({ content: "文件名不能超过20个字", color: 'warning', duration: 10 });
                    return false
                }
            },
            splitFileName(text) {//用正则表达式去去除文件后缀
                var pattern = /\.{1}[a-z]{1,}$/;
                if (pattern.exec(text) !== null) {
                    return (text.slice(0, pattern.exec(text).index));
                } else {
                    return text;
                }
            },
            onChange(info) {
                if (info.file.status !== 'uploading') {
                }
                if (info.file.status === 'done') {
                    let res = info.file.response;
                    if (res.status == 0) {
                        Message.create({ content: res.message, color: 'danger', duration: 10 });
                        return;
                    }
                    let name = info.file.name.split(".");
                    let type = name[name.length - 1];
                    let { filename, uploadtime, url } = res.data[0];
                    let fileData = {
                        filename: filename,
                        creationTime: new Date(uploadtime).getTime(), //uploadtime
                        creator: personName,
                        fileUrl: url,
                        type: type,
                        persistStatus: "new"
                    }

                    _this.onCloseEdit(fileData, "confirmAttachments")
                } else if (info.file.status === 'error') {

                }
            }
        };

        Object.keys(childTableColumn).forEach(function (item) {

            let dom;
            hidepage = childTableColumn[item].hidepage;
            if (hidepage && hidepage[btnPageFlag]) {
                showpage = false;
            } else {
                showpage = true;
            }
            tempColumn = cloneDeep(childTableColumn[item]);
            type = childTableColumn[item].type;
            if (showpage && type == "grid") {
                gridData = rowData[item] || [];
                if (!rowData[item]) rowData[item] = [];
                _column = tempColumn && tempColumn.column || {};
                // if ((item == "mrjtCustomerAddressList" || item == "mrjtCustomerContactList" || item == "mrjtCustomerFinanceList" || item == "mrjtCustomerAccountList") && btnPageFlag == 2) {
                //     _column = _this.pushOper(_column, item);
                // }
                let billState=rowData.state;
                if (item == "confirmAttachments") {
                    _column = _this.pushOper(_column, item, billState);
                }
                btnPageFlag = _this.state.btnPageFlag;
                let getDealFlag = _this.props.location.search;
                if(item=="confirmConnects"){
                    hideBtns = {"add":true,"del":true,"copy":true};
                }else if(getDealFlag.indexOf("getDealFlag")!=-1){
                    hideBtns = {"add":true};
                }else{
                    hideBtns = {};
                }
                dom = <div className="gird-parent">
                    {item == "confirmAttachments" && <Upload {...fileUpload}> <Button
                        key={item}
                        shape="border"
                        className="ml8 addtable"
            ><Icon type="uf-upload" />上传</Button></Upload>}
               

                    <EditGrid
                        showIndex={true}
                        disabled={btnPageFlag == 2}
                        btnPageFlag={btnPageFlag}
                        defaultOpen={true}
                        columns={_column}
                        data={gridData}
                        childType={item}
                        hideBtns={hideBtns}
                        paginationObj={"none"}
                        multiSelect={true}
                        onChange={_this.onEditGridChange}
                        defaultValueObj={childTableColumn[item].defaultValueObj}
                        showPagination={false}
                        onValidate={onEditGridValidate}
                        onDel={_this.onEditGridDel}
                        beforeAddRow={_this.beforeAddRow}
                        loading={{ show: showLoading }}
                        fileEditFlag={item == "confirmAttachments"}
                    />

                    {/* <Grid
                        ref={(el) => _this.grid = el} //存模版
                        data={rowData[item]}
                        rowKey={Math.random()}
                        columns={_column}
                        paginationObj={'none'}
                        multiSelect={false}
                        showHeaderMenu={true}
                        sort={sortObj} //后端排序
                        loading={{ show: showLoading, }}
                        scroll={{ y: tableHeight }}
                        sheetHeader={{ height: 30, ifshow: false }}
                    /> */}
                </div>;
                FormDom.push(<CollapsePanel in={!tempColumn.collapse} key={tempColumn.title} title={tempColumn.title}>
                    {dom}
                </CollapsePanel>)
            } else if (showpage && type == "table") {
                let tableData = rowData[item] || [];

                // if (item == "relateCustomerList" && aliaCustomerList) {
                //     tableData = aliaCustomerList;
                // }
                dom = <Grid
                    paginationObj={'none'}
                    multiSelect={false}
                    data={tableData}
                    rowKey={(r, i) => i}
                    columns={tempColumn.column}
                />;
                FormDom.push(<CollapsePanel in={!tempColumn.collapse} key={tempColumn.title} title={tempColumn.title}>
                    {dom}
                </CollapsePanel>)
            }
        })

        console.log(FormDom);
        return FormDom;
    }

    ButtonApprovalCal = (res) => {
        let searchObj = queryString.parse(this.props.location.search);
        let { from } = searchObj;
        if(from == "approveCenter") {
            let data = {
                id: "approveCenter",
                router: "/mcc-portal-react/base/index.html#approveCenter",
                title: "审批任务"
            }
            if(res.code==='1'){//出错不跳转code=0为成功1为失败
                return false
            }else{
                // actions.ExpenseConfirmation.queryDetail(param);
                location.reload();
                window.top.handleClick(null,1,data);
            }
        }else if( from == "messageCenter") {
            let data = {
                id: "messageCenter2",
                router: "/mcc-portal-react/base/index.html#messageCenter",
                title: "消息列表"
            }
            window.top.handleClick(null,1,data);
        }else {
            actions.routing.push(
                {
                    pathname: '/ExpenseConfirmation-list',
                }
            )
        }
        
    }

    beforeAddRow = (childType, callback) => {
        let { form, rowData } = this.props;
        let values = form.getFieldsValue(["settlementId","organizationId","customerId", "dutyPersonId", "custchantypeId","commoditybrandId","goodscategoryId","shopId","feeitemId","marketareaId"]);
        if (!values.cpaydeptidId) {
            values["cpaydeptidId"] = values.marketareaId;
        }
        values = onHandleChildObj(values, "0").values;
        values.year = moment();
        values.month = moment();
        values.headFeeItemShadowCode = values.feeitemCode;
        if(values.settlementCode == "13" || values.settlementCode == "12") {
            values.taxNum = 13;
        }else if(values.settlementCode == "21"){
            values.taxNum = 6;
        }else{
            values.taxNum = 0;
        }
        
        delete values.feeitemId;
        delete values.feeitemCode;
        delete values.feeitemName;
        
        callback && callback({ [childType]: values });
    }

    ExppenseRedInk = () => {
        let {rowData} = this.props;
        if(rowData.confirmSon.length == 0) {
            Message.create({ content: `请先添加字表`, color: 'warning', duration: 10 });
            return;
        }
        this.setState({
            showExpenseRedInk:true
        })
    }

    ExpenseRedInkCallback = (type) => {
        if(type) {
            this.onBack();
        }else {
            this.setState({
                showExpenseRedInk:false
            })
        }
    }

    ButtonUpdateCheck = () => {
        let searchObj = queryString.parse(this.props.location.search);
        let { from } = searchObj; 
        let { rowData } = this.props;
        if(from == "approveCenter" && rowData.billStatusCode!=='3') {
            return true;
        }else{
            return false;
        }
    }

    ButtonSaveCheck = () => {
        let { rowData } = this.props;
        //判断是否有没有红冲的明细
        if(rowData && rowData.ext04=="Y" && rowData.confirmSon){
            rowData.ext05 = "否";
            rowData.confirmSon.filter(item=>{
                if (parseFloat(item.confirmamount/item.plancostamount).toFixed(2)>0.80) {
                    item.ext05 = "是";
                    rowData.ext05 = "是";
                }else{
                    item.ext05="否"
                }
            })
        }
        if (rowData.ext05 == "是") {
            return true;
        }else{
            return false;
        }
    }

    ButtonExppenseRedInkCheck = () => {
        let { rowData } = this.props;
        let key = "N";
        //判断是否有没有红冲的明细
        if(rowData && rowData.state==3 && rowData.confirmSon){
            rowData.confirmSon.filter(item=>{
                if (item.isoppose==0) {
                    key = "Y";
                }
            })
        }
        if(rowData && rowData.state==3 && key ==="Y" && rowData.redbillcode==null 
            && !(rowData.billtypeCode==="35-Cxx-005")) {
            return true;
        }else{
            return false;
        }
    }
    

    render() {
        let { editModelVisible, selectedIndex, btnFlag, tableHeight, search_id,
            delModalVisible, currentlist, ColumnsData, btnPageFlag, childType } = this.state;
        let { childTableColumn, FormField, FormTableField } = this.state;
        let {rowData={}} = this.props;
        let authCodeList = JSON.parse(sessionStorage.getItem("ExpenseConfirmation") || "[]");
        let sortObj = {
            mode: 'multiple',
            backSource: true
        }
        if(typeof btnPageFlag == "undefined") {return <></>};
        let rowDataArray = [];
        rowDataArray.push(this.props.rowData);
        let { getFieldProps } = this.props.form;
        let bpmService = {
            "ButtonSubmit": {
                url: `/occ-fee/fee/confirms/batch/submit?billCode=billcode`,
                code: "0",  //自由
                field: "state",
                authCode: "Confirmationsubmit",
            },
            "ButtonCallback": {
                url: `/occ-fee/fee/confirms/batch/taskback`,
                code: "1",
                field: "state",
                authCode: "Confirmationreject",
            },
            "ButtonApprove": {
                url1: `/occ-fee/fee/confirms/batch/complete?billCode=billcode`,
                url: `/occ-fee/fee/confirms/batch/judgeProcess`,
                code: "1,2",
                field: "state",
                authCode: "Confirmationapprove",
            },
            // "ButtonCancelApprove": {
            //     url: `/occ-fee/fee/confirms/batch/withdrawtask`,
            //     code: "2",
            //     field: "state",
            //     authCode: "Confirmationcancel",
            // },
            "CheckApprove": {
                url: `/occ-cmpt/bpm/processoper/historictasks`,
                code: "0,1,2,3",
                field: "state",
                authCode: "Confirmationsubmit",
            }
        }
        let pagetitle = this.onChangeHead(btnPageFlag);
        return (
            <div className='single-table-popup ExpenseConfirmation-detail'>

                <Header title={pagetitle} back={true} backFn={this.onBack}>
                    {(btnPageFlag != 2 && btnPageFlag != 5) ? (
                        <div className='head-btn'>
                            <Button className='head-save' onClick={this.onBack}>取消</Button>
                            {(rowData&&this.ButtonSaveCheck())?(
                                <DelModal selectData={[{}]} modalTitle="提示" modalContent="费用确认金额占决裁金额超80%，是否继续？" confirmFn={this.save}>
                                {<Button className='head-save'>保存</Button>}
                                </DelModal>)
                            :(<Button className='head-save' onClick={this.save}>保存</Button>)} 
                        </div>
                    ) : (<div className='head-btn'>
                        {authCodeList.indexOf("9901-05-03-06")!==-1 && btnPageFlag != 5 && <Button className='head-cancel' onClick={this.onToEdit(1)}>编辑</Button>}
                        {/* <DelModal selectData={[{}]} modalTitle="删除" modalContent="确认删除？" confirmFn={this.onDel}>
                        {rowData.isEnable != 1 && <Button className='head-save'>删除</Button>}
                        </DelModal> */}
                        {/* <Button className='head-save' onClick={this.onToEdit(3)}>复制</Button> */}
                        {this.ButtonExppenseRedInkCheck() && <Button className='head-save' onClick={this.ExppenseRedInk}>费用红冲</Button>}
                        {this.ButtonUpdateCheck() && <Button className='head-save' onClick={this.onToEdit(1)}>修改</Button>}
                        <Button className='head-save' onClick={this.syncNCC}>同步NCC</Button>
                        {rowData.state == 3 && authCodeList.indexOf("ConfirmationReceive")!==-1 && <Button className='head-save' onClick={this.ButtonSignReceive}>标记签收</Button>}
                        {rowData.state == 3 && authCodeList.indexOf("ConfirmationPay")!==-1 && <Button className='head-save' onClick={this.ButtonSignPay}>标记支付</Button>}
                        {rowData.state == 3 && authCodeList.indexOf("ConfirmationDisPay")!==-1 && <Button className='head-save' onClick={this.ButtonDisSignPay}>取消支付</Button>}
                        {<Button className='head-save' onClick={this.collectBill}>收藏单据</Button>}
                        {<Button className='head-save' onClick={this.cancelCollectBill}>取消收藏</Button>}
                        {rowData.isEnable == 1 && <PurchaseApprovalButton
                            selectData={rowDataArray}
                            billType="CUAP"
                            printTemplateId="1001A61000000001R3LU"
                            ButtonApprovalCal={this.ButtonApprovalCal}
                            authCodeList={authCodeList}
                            modalName = "ExpenseConfirmation"
                            bpmService={bpmService}
                        />}
                    </div>)
                    }
                </Header>
                {this.renderFormFiled()}
                {this.renderTableFiled()}

                <Alert show={delModalVisible}
                    context={this.state.modalContent || "确定操作？"}
                    confirmFn={() => {
                        this.confirmGoBack(1);
                    }}
                    cancelFn={() => {
                        this.confirmGoBack(2);
                    }}
                />
                {this.props.rowData.confirmSon.length>0 && <ExpenseRedInkModal
                    showExpenseRedInk={this.state.showExpenseRedInk}
                    rowData={this.props.rowData}
                    ExpenseRedInkCallback={this.ExpenseRedInkCallback}
                    
                />}
            </div >
        )

    }
}

export default Form.createForm()(Edit);


